import GoogleMobileAds
import FirebaseRemoteConfigInternal
import FirebaseCore
import FacebookCore
import AppTrackingTransparency

class AppDelegate: UIResponder, UIApplicationDelegate {
    
    func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool{
        
        FirebaseApp.configure()
        getFirebaseMessage()
        GADMobileAds.sharedInstance().start(completionHandler: nil)
        
        // 初始化 Facebook SDK
        ApplicationDelegate.shared.application(
            application,
            didFinishLaunchingWithOptions: launchOptions
        )
        
        ApplicationDelegate.shared.initializeSDK()
        
        
      //  getFaceLink()
        
        
        // 初始化 Singular SDK
        
//        if let config = getConfig() {
//            Singular.start(config)
//        }
        
        //logData(position: "初始化", status: "初始化完成", uid: "", info: "进入APP初始化完成", currency: "", cicros: "")
        
        
        return true
    }
    
    //Facebook激活上报
//    func applicationDidBecomeActive(_ application: UIApplication) {
//        AppEvents.shared.activateApp()
//    }
    
    
    
    func application(_ application: UIApplication,open url: URL,sourceApplication: String?,annotation: Any) -> Bool {
        
        
        return ApplicationDelegate.shared.application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)
    }
    
    
    
    
    //配置SingularConfig
//    func getConfig() -> SingularConfig? {
//        guard let config = SingularConfig(apiKey: singularKey, andSecret:singularSecret) else {
//            return nil
//        }
//        
//        config.waitForTrackingAuthorizationWithTimeoutInterval = 30
//        
//        
//        print("xianban singular init success ")
//        config.singularLinksHandler = { params in
//            print("xianban parms:\(String(describing: params))")
//            self.handleDeeplink(params: params)
//        }
//        
//        
//        config.deviceAttributionCallback = {attributionInfo in
//            if let jsonData = try? JSONSerialization.data(withJSONObject: attributionInfo, options: .prettyPrinted),
//               let jsonString = String(data: jsonData, encoding: .utf8) {
//                //logData(position: "singular", status: jsonString, uid: "", info: "安装归因信息回调上传", currency: "", cicros: "",deepLink:  "")
//                
//            } else {
//                print("无法将归因信息转换为 JSON 字符串")
//            }
//        }
//        
//        return config
//    }
    
    
    //获取firebase消息
    func getFirebaseMessage(){
        let remoteConfig = RemoteConfig.remoteConfig()
        let settings = RemoteConfigSettings()
        settings.minimumFetchInterval = 0
        remoteConfig.configSettings = settings
        
        
        remoteConfig.fetch { (status, error) -> Void in
            if status == .success {
                remoteConfig.activate { changed, error in
                    if error == nil {
                        let openStatus = remoteConfig.configValue(forKey: "openStatus").boolValue ?? false
                        
                        UserDefaultsManager.shared.setBool(openStatus, forKey:"openStatus")
                    } else {
                        print("fetched激活配置时出错: \(error?.localizedDescription ?? "未知错误")")
                    }
                }
            } else {
                print("fetchedError: \(error?.localizedDescription ?? "No error available.")")
            }
        }
    }
    // 从 Singular Link 获取深度链接数据
//    func handleDeeplink(params: SingularLinkParams?) {
//        
//        let deeplink = params?.getDeepLink()
//        let passthrough = params?.getPassthrough()
//        let isDeferredDeeplink = params?.isDeferred()
//        print("xianban deep Link:\(String(describing: deeplink))")
//        UserDefaultsManager.shared.setString(String(describing: deeplink), forKey: "referer")
//        
//    }
    
    //获取IDFA,初始化singular
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession,options connectionOptions: UIScene.ConnectionOptions) {
        let userActivity = connectionOptions.userActivities.first
        // 将 IDFV 打印到控制台，供 Singular SDK 控制台使用
        print(Date(), "-- Scene Delegate IDFV:",
              UIDevice().identifierForVendor!.uuidString as Any)
        print("init")
        // 在此初始化 Singular SDK：
//        if let config = self.getConfig() {
//            config.userActivity = userActivity
//            Singular.start(config)
//        }
    }
    
    // 通过 continueUserActivity 启动新的 Singular 会话
    func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
//        
//        if let config = self.getConfig() {
//            config.userActivity = userActivity
//            Singular.start(config)
//        }
    }
    
    
    
    
    
    func application( _ app: UIApplication,  open url: URL,  options: [UIApplication.OpenURLOptionsKey : Any] = [:] ) -> Bool {
        
        // 调用ApplicationDelegate的处理方法
        ApplicationDelegate.shared.application(
            app,
            open: url,
            sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
            annotation: options[UIApplication.OpenURLOptionsKey.annotation]
        )
        
        
        getFaceLink()
        
        // 打印传入的URL
        UserDefaultsManager.shared.setString(String(describing: url), forKey: "iosLink")
        
        
        return true
    }
    
}


func getFaceLink(){
    AppLinkUtility.fetchDeferredAppLink { (url, error) in
        
        if let error = error {
            
            //logData(position: "facebook", status: "Facebook Link", uid: "", info: "facebook错误,\(String(describing: error))", currency: "", cicros: "")
            
        }
        
        if let url = url {
            
            UserDefaultsManager.shared.setString(url.absoluteString, forKey: "fbLink")
            //logData(position: "facebook", status: "Facebook Link", uid: "", info: "直传深度链接", currency: "", cicros: "",errorInfo:  url.absoluteString)
            
            print("facebook11 link error111", url.absoluteString)
            if #available(iOS 10, *) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            } else {
                
                
                UIApplication.shared.openURL(url)
            }
        }
    }
}

